(() => {
  class Game {
    constructor(map) {
      this.food = new Food();
      this.snake = new Snake();
      this.map = map;
    }
    start() {
      this.food.render(this.map);
      this.food.render(this.map);
      this.food.render(this.map);
      this.bindkey();
      this.runsnake();
      this.snake.render(this.map);
    }
    runsnake() {
      let timer = setInterval(() => {
        this.snake.move();
        this.snake.remove(this.map);
        this.snake.render(this.map);

        // 最大的位置
        let maxX = this.map.clientWidth / this.snake.width;
        let maxY = this.map.clientHeight / this.snake.height;
        //蛇头的位置
        let headX = this.snake.body[0].x;
        let headY = this.snake.body[0].y;

        let snakeHeadX = headX * this.snake.width;
        let snakeHeadY = headY * this.snake.height;
        if (headX < 0 || headX >= maxX || headY < 0 || headY >= maxY) {
          clearInterval(timer);
          alert("Game over");
        }
        for (var i = 0; i < this.food.elemntArr.length; i++) {
          if (
            snakeHeadX === this.food.elemntArr[i].offsetLeft &&
            snakeHeadY === this.food.elemntArr[i].offsetTop
          ) {
            this.food.remove(this.map, i);
            this.food.render(this.map);
            let lastfood = this.snake.body[this.snake.body.length - 1];
            this.snake.body.push({
              x: lastfood.x,
              y: lastfood.y,
              color: lastfood.color,
            });
          }
        }
      }, 200);
    }
    bindkey() {
      document.onkeydown = (e) => {
        switch (e.keyCode) {
          case 37:
            this.snake.direction = "left";
            break;
          case 38:
            this.snake.direction = "top";
            break;
          case 39:
            this.snake.direction = "right";
            break;
          case 40:
            this.snake.direction = "bottom";
            break;
        }
      };
    }
  }
  window.Game = Game;
  //   const map = my$("map");
  //   const games = new Game(map);
  //   games.bindkey();
  //   games.runsnake();
  //   games.start();
})();
